package MyApp::Workflow::Action::AgreeMac;

use strict;
use base qw( Workflow::Action );
use Workflow::Exception qw( persist_error );
use Workflow::Factory qw( FACTORY );

sub execute {
    my ($self,$wf) = @_;
    my $db=$wf->context->param('db');

    my $issue_id = $db->query('select number from daiban where workflow_id=? AND workflow_type=3',
                              $wf->id)->array->[0];
    my $mac_hashes = $db->query('select * from mac_application where issue_id=?',
                                     $issue_id)->hashes;
    
    foreach my $hash (@$mac_hashes) {
        if ($hash->{operation} == 1) {
            #my $company_name = $db->query('select name from company_application where id=?',$hash->{company_id})->array->[0];
            $db->query('insert into maclist (mac,company,tibaoren,issue_id) values (?,?,?,?)',
                        $hash->{mac},$hash->{company_id},$wf->context->param('creator'),$hash->{issue_id});
            $db->query('insert into mac_dealing (mac,operation) values (?,1)',
                        $hash->{mac});
        } elsif ($hash->{operation} == 0) {

            #my $company_name = $db->query('select name from company_application where id=?',$hash->{company_id})->array->[0];
            #检查MAC地址是否还在处理表中未添加：
            my $array = $db->query('select mac,operation from mac_dealing where mac=?',$hash->{mac})->array;
            if ($array->[0]) {
                next if $array->[1] == 0;
                $db->query('delete from mac_dealing where mac=?',$hash->{mac});
                $db->query('delete from maclist where mac=?',$hash->{mac});
                $db->query('update daiban set is_finish=1 where workflow_type=3 and workflow_id=?',$wf->id);
                next;
            }

            #当MAC删除时，MAC处理列表中插入数据（处理完成后再删除台账表中数据）
            $db->query('insert into mac_dealing (mac,operation) values (?,0)',
                        $hash->{mac});
         
        } else {
          #公司业务转移，将MAC地址转移到新公司，操作代码operation为2：
          $db->query('update maclist set company=?,tibaoren=?,issue_id=? where mac=?',$hash->{company_id},$wf->context->param('creator'),$hash->{issue_id},$hash->{mac});
        }

        $db->query('update daiban set is_finish=1 where workflow_type=3 and workflow_id=?',$wf->id);
    }

    $wf->add_history(
        Workflow::History->new({
            action      => '审核',
            description => sprintf("同意!"),
            user        => $wf->context->param('current_user'),
            time_zone   => 'local'
        })
    );
};

1;
